/**
 * Created by way on 2016/12/20.
 * 大转盘抽奖，指针或背板都能转动
 */

export default class {
  constructor(pad, pointer) {
    this.angle = 0; // 起始位置为0
    this.run = false; // 正在转动，不可再次触发
    this.pad = pad;
    this.pointer = pointer;
  }

  /**
   * 转动转盘
   * @param type
   * @param during
   * @param id  获奖id
   * @param angle 角度
   * @param cb
   */
  start(type, during, angle, cb) { // type:0,箭头转动, 1,背景转动; during:持续时间(s)
    if (this.run || angle < 0 || angle > 360)
      return;

    this.run = true; // 旋转结束前，不允许再次触发

    type = type || 0; // 默认为箭头转动
    during = during || 1; // 默认为1s

/*  这段代码要放到服务器端，否则会被攻击！！！
    let id; // 最终要旋转到哪一块，对应result_angle的下标
    let startPos = 0;
    let endPos = 0; // 判断的角度值起始位置和结束位置

    // 计算随机数在哪个奖品区域
    const rand = Math.ceil(Math.random() * 100); // 用来判断的随机数，1-100
    for (let i = 0, l = gifts.length; i < l; i++) {
      startPos = endPos; // 区块的起始值
      endPos += 100 * gifts[i].p; // 区块的结束值
      if (rand > startPos && rand <= endPos) { // 如果随机数落在当前区块，那么获取到最终要旋转到哪一块
        id = i;
        break;
      }
    }
*/
    const circle = Math.ceil(Math.random() * 2) + 1; // 附加多转几圈，2-3
    let turn = null;

    if (type === 1) {  // 转动盘子
      this.angle = this.angle - circle * 360 - angle - this.angle % 360;
      turn = this.pad;
    } else {
      this.angle = this.angle + circle * 360 + angle - this.angle % 360;
      turn = this.pointer;
    }

    // 通过样式转动，通过 cavance 也可以转动
    turn.style.webkitTransform = turn.style.MozTransform
      = turn.style.transform = `rotate(${this.angle}deg)`;

    turn.style.webkitTransition = turn.style.MozTransition
      = turn.style.transition = `transform ease-out ${during}s`;
/*
      + `-webkit-transform: rotate(${this.angle}deg);`
      + `-moz-transform: rotate(${this.angle}deg);`
      + `-o-transform: rotate(${this.angle}deg);`
      + `transition: transform ease-out ${during}s;`
      + `-moz-transition: -moz-transform ease-out ${during}s;`
      + `-webkit-transition: -webkit-transform ease-out ${during}s;`
      + `o-transition: -o-transform ease-out ${during}s;`;
*/
    // 旋转结束后，允许再次触发
    setTimeout(() => {
      if (cb)
        cb();
      this.run = false;
      // turn.style = '';
      // 告诉结果
      // alert(gifts[rs].t);
    }, during * 1000);
  }
}
